<template>
  <div class="auth-role-container">
    <el-button size="small" type="primary" @click="saveAuth">保 存</el-button>
    <el-divider />
    <el-tree
      ref="menuTree"
      :data="menus"
      :default-checked-keys="hasMenu"
      :props="menuDefaultProps"
      default-expand-all
      highlight-current
      node-key="menu_name"
      show-checkbox
      check-strictly
    />
  </div>
</template>

<script>
import { getAllMenus } from '@/api/menu'
import { authRole } from '@/api/role'
export default {
  name: 'AuthRole',
  components: {},
  props: {
    editRoleInfo: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      menus: [],
      hasMenu: [],
      menuDefaultProps: {
        children: 'children',
        label: function (data) {
          return data.title
        }
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.setHasMenu()
    this.getAllMenus()
  },
  mounted () {},
  methods: {
    setHasMenu: function () {
      if (this.editRoleInfo.auths) {
        this.hasMenu = this.editRoleInfo.auths.split(',')
      }
    },
    getAllMenus: async function () {
      const res = await getAllMenus()
      this.menus = res
    },
    saveAuth: async function () {
      const checkMenuId = this.$refs.menuTree.getCheckedKeys(false)
      const data = {
        id: this.editRoleInfo.id,
        auths: checkMenuId.join(',')
      }
      const res = await authRole(data)
      if (!res) return this.$message({ message: '没有改动!', type: 'error', duration: 1000 })
      this.$message({ message: '授权成功', type: 'success', duration: 1000 })
      this.$emit('reset-roles')
    }
  }
}
</script>

<style scoped lang="scss">
.auth-role-container {
  padding: 0 20px;
}
</style>
